# This file is executed on every boot (including wake-boot from deepsleep)
# import esp
# esp.osdebug(None)
# import webrepl
# webrepl.start()
# print("varin")

from machine import Pin, SPI
from st7735 import ST7735, color
from ufont import BMFont
import time
import random
import network
import ntptime
from machine import RTC
import time

rtc = RTC()

font = BMFont("font.bmf")
#  WIFI名称和连接密码
ssid = "aaa"
password = "12345678"

spi = SPI(1, baudrate=60_000_000, polarity=0, sck=Pin(2), mosi=Pin(3), miso=None)
tft = ST7735(spi, rst=10, dc=6, cs=7, bl=8, width=160, height=127, offset=(-1, 0), rotate=1, rgb=True)


def network_connect():
    font.text(tft, "WIFI网络连接中~", 0, 0,
              color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
              reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    # 判断WIF是否连接，如无连接通过循环等待WIFI连接后再执行后续代码
    if not sta.isconnected():
        sta.connect(ssid, password)
        while not sta.isconnected():
            pass
        print(sta.ifconfig())
        ntptime.settime()
        print()
        font.text(tft, "WIFI网络连接成功~", 0, 0,
                  color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
                  reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
        font.text(tft, "WIFI名称为：" + ssid, 0, 20,
                  color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
                  reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
        font.text(tft, "IP地址：" + sta.ifconfig()[0], 0, 40,
                  color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
                  reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
        while True:
            # 实时更新屏幕时间
            t = rtc.datetime()
            timeStr = '当前时间是：{}:{}:{}'.format(t[4] + 8, t[5], t[6])
            font.text(tft, timeStr, 0, 60,
                      color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
                      reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
            font.text(tft, "今天又是加油的一天呀", 0, 80,
                      color(random.randint(1, 256), random.randint(1, 256), random.randint(1, 256)), font_size=16,
                      reverse=False, clear=False, show=True, half_char=True, auto_wrap=False)
            time.sleep(1)


if __name__ == "__main__":
    network_connect()



